package com.bootdo.haojiangboutils;


import java.lang.reflect.Field;
import java.util.List;

/**
 *
 * 新返回值构造器
 　　* @author 郝江波
 　　* @date 2019/9/9 18:36
 　　*/
public class ResultReBuild <T>{
    /**
     * 只保留传入的字段的值
     * @param t
     * @param fields
     * @return
     */
    public T toNewObj(T t, String ... fields){

        Object result = null;
        try {
            Class clazz =  t.getClass();
            result = clazz.newInstance();
            for(String f : fields){
                Field field = clazz.getDeclaredField(f);
                field.setAccessible(true);
                field.set(result, field.get(t));
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return (T) result;
    }

    /**
     * 转换list里的值
     * @param list
     * @param fields
     * @return
     */
    public List<T> toNewObj(List<T> list, String ... fields){
        for(int i = 0; i < list.size(); i++){
            T t = list.get(i);
            Object result = null;
            try {
                Class clazz =  t.getClass();
                result = clazz.newInstance();
                for(String f : fields){
                    Field field = clazz.getDeclaredField(f);
                    field.setAccessible(true);
                    field.set(result, field.get(t));
                }
                list.set(i, (T)result);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        return  list;
    }


}
